package com.eibus.applicationconnector.twitter;

import twitter4j.Twitter;

import com.cordys.coe.exception.GeneralException;
import com.cordys.coe.util.XMLProperties;
import com.eibus.connector.nom.Connector;
import com.eibus.soap.BodyBlock;
import com.eibus.soap.Processor;
import com.eibus.soap.SOAPTransaction;
import com.eibus.xml.nom.Document;
import com.eibus.xml.nom.Find;
import com.eibus.xml.nom.Node;

public class TwitterTransaction implements com.eibus.soap.ApplicationTransaction{

	private static final String SERVICE_TYPE = "TWITTERSERVICE";

	private TwitterConnector connector;
	private Processor processor;
	private SOAPTransaction soapTransaction;
	public TwitterTransaction(Processor processor,
			SOAPTransaction soapTransaction,TwitterConnector connector) {
		
		this.connector=connector;
		this.processor=processor;
		this.soapTransaction=soapTransaction;
	}

	@Override
	public void commit() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void abort() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public boolean canProcess(String paramString) {
		 return SERVICE_TYPE.equals(paramString);
	}

	@Override
	public boolean process(BodyBlock request, BodyBlock response) {
		int requestNode = request.getXMLNode(); 
		String command = Node.getLocalName(requestNode);    
		
		
		boolean bResult = false;

	        try
	        {
	            int iReqNode = request.getXMLNode();

	            if (iReqNode == 0)
	            {
	                throw new Exception("No actions specified in the request.");
	            }

	            String sAction = getActionFromImplementation(request);

	         

	            ITwitterMethod method = connector.getMethod(sAction);

	            // Pass the control to the right handler object.
	            if (method != null)
	            {
	                ISoapRequestContext req = new SoapRequestImpl(request, response);

	                bResult = method.process(req) == ITwitterMethod.EResult.FINISHED;
	            }
	            else
	            {
	                throw new Exception("Unknown action '" + sAction + "'");
	            }
	        }
	        catch (Throwable e)
	        {
	           

	            response.createSOAPFault("Server.Exception", e.toString());

	            return false;
	        }

	      

	        return bResult;
	
	}
	
	private String getActionFromImplementation(BodyBlock bbRequest)
    {
        String sAction;

        int iImplNode = bbRequest.getMethodDefinition().getImplementation();
        int actionNode = Find.firstMatch(iImplNode, "<implementation><action>");

        if (actionNode != 0)
        {
            sAction = Node.getData(actionNode);
        }
        else
        {
            // For backwards compatibility
            sAction = Node.getLocalName(bbRequest.getXMLNode());
        }

        return sAction;
    }

	
	
	   /**
     * Implementation of the ISoapRequestContext for application connector SOAP requests.
     *
     * @author  mpoyhone
     */
    private class SoapRequestImpl
        implements ISoapRequestContext
    {
        /**
         * Request body block.
         */
        private BodyBlock requestBlock;
        /**
         * Response body block.
         */
        private BodyBlock responseBlock;

        /**
         * Constructor for SoapRequestImpl.
         *
         * @param  requestBlock
         * @param  responseBlock
         */
        public SoapRequestImpl(BodyBlock requestBlock, BodyBlock responseBlock)
        {
            super();
            this.requestBlock = requestBlock;
            this.responseBlock = responseBlock;
        }

        /**
         * @see  com.cordys.coe.ac.fileconnector.ISoapRequestContext#addResponseElement(java.lang.String)
         */
        public int addResponseElement(String elemName)
        {
            return Node.createElement(elemName, responseBlock.getXMLNode());
        }

        /**
         * @see  com.cordys.coe.ac.fileconnector.ISoapRequestContext#addResponseElement(int)
         */
        public int addResponseElement(int node)
        {
            return Node.appendToChildren(node, responseBlock.getXMLNode());
        }

        /**
         * @see  com.cordys.coe.ac.fileconnector.ISoapRequestContext#addResponseElement(java.lang.String,
         *       java.lang.String)
         */
        public int addResponseElement(String elemName, String elemValue)
        {
            return Node.createTextElement(elemName, elemValue, responseBlock.getXMLNode());
        }

        /**
         * @see  com.cordys.coe.ac.fileconnector.ISoapRequestContext#getMethodImplementation()
         */
        public int getMethodImplementation()
        {
            return requestBlock.getMethodDefinition().getImplementation();
        }

       

        /**
         * @see  com.cordys.coe.ac.fileconnector.ISoapRequestContext#getNomDocument()
         */
        public Document getNomDocument()
        {
            return Node.getDocument(responseBlock.getXMLNode());
        }

        /**
         * @see  com.cordys.coe.ac.fileconnector.ISoapRequestContext#getRequestAsXmlProperties()
         */
        public XMLProperties getRequestAsXmlProperties()
                                                throws GeneralException
        {
            return new XMLProperties(requestBlock.getXMLNode());
        }

        /**
         * @see  com.cordys.coe.ac.fileconnector.ISoapRequestContext#getRequestOrganizationDn()
         */
        public String getRequestOrganizationDn()
        {
            return connector.getProcessor().getOrganization();
        }

        /**
         * @see  com.cordys.coe.ac.fileconnector.ISoapRequestContext#getRequestRootNode()
         */
        public int getRequestRootNode()
        {
            return requestBlock.getXMLNode();
        }

        /**
         * @see  com.cordys.coe.ac.fileconnector.ISoapRequestContext#getRequestUserDn()
         */
        public String getRequestUserDn()
        {
            return requestBlock.getSOAPTransaction().getUserCredentials().getOrganizationalUser();
        }

        /**
         * @see  com.cordys.coe.ac.fileconnector.ISoapRequestContext#getResponseRootNode()
         */
        public int getResponseRootNode()
        {
            return responseBlock.getXMLNode();
        }
    }
}
